<template>
  <div class="app-container">
    <ContentWrap>
      <el-row :gutter="20">
        <el-col :span="4">
          <RegionTree ref="refDfqRegionTree" nodeType="3" :treeLoaded="handleTreeLoaded" :node-click="handleNodeClick"/>
        </el-col>

        <el-col :span="20" class="content-container">
          <div style="margin-bottom: 5px;">
            当前大用户：<span style="color: #1890ff;">{{ editingZone ? editingZone.areaName : '无' }}</span>
          </div>
          <div style="display: flex;justify-content: space-between;margin-bottom: 5px;">
            <div class="data-item">
              <div>
                <img :src="require('@/assets/leakage/daily_water.png')" alt="" style="width: 56px;height: 56px;">
              </div>
              <div>
                <div style="font-size: 20px;padding: 5px;">昨日用水量</div>
                <div class="value">
                  {{
                    dyhDailyUsed
                  }}
                  <span style="font-size: 16px;">m³</span>
                </div>
              </div>
            </div>

            <div style="border: 1px solid #E3E3E3;">
              <div
                style="background-color: #0096ff;padding: 8px 5px;color: #FFFFFF;font-size: 16px;font-weight:bold;text-align: center;">
                大用户昨日用水量占比
              </div>

              <div style="display: flex;">
                <div style="width: 200px;padding: 10px;">
                  <div style="font-size: 16px;">其他大用户昨日用水量</div>
                  <div style="font-size: 22px;margin: 5px;">
                    {{
                      dyhDailyOther
                    }}
                    <span style="font-size: 16px;">m³</span>
                  </div>
                  <div style="font-size: 16px;">当前大用户用水占比</div>
                  <div style="font-size: 22px;margin: 5px;">
                    {{
                      dyhDailyUsed ? ((dyhDailyUsed / dyhDailyOther) * 100.0).toFixed(2) : 0
                    }}
                    <span style="font-size: 16px;">%</span>
                  </div>
                </div>

                <div id="dyh-daily-chart" style="width: 200px;height: 140px;"></div>
              </div>
            </div>

            <div class="data-item">
              <div>
                <img :src="require('@/assets/leakage/monthly_water.png')" alt="" style="width: 56px;height: 56px;">
              </div>
              <div>
                <div style="font-size: 20px;padding: 5px;">上月用水量(m³)</div>
                <div class="value">
                  {{
                    dyhMonthlyUsed
                  }}
                  <span style="font-size: 16px;">m³</span>
                </div>
              </div>
            </div>

            <div style="border: 1px solid #E3E3E3;">
              <div
                style="background-color: #0096ff;padding: 8px 5px;color: #FFFFFF;font-size: 16px;font-weight:bold;text-align: center;">
                大用户上月用水量占比
              </div>

              <div style="display: flex;">
                <div style="width: 200px;padding: 10px;">
                  <div style="font-size: 16px;">其他大用户上月用水量</div>
                  <div style="font-size: 22px;margin: 5px;">
                    {{
                      dyhMonthlyOther
                    }}
                    <span style="font-size: 16px;">m³</span>
                  </div>
                  <div style="font-size: 16px;">当前大用户用水占比</div>
                  <div style="font-size: 22px;margin: 5px;">
                    {{
                      dyhMonthlyUsed ? ((dyhMonthlyUsed / dyhMonthlyOther) * 100.0).toFixed(2) : 0
                    }}
                    <span style="font-size: 16px;">%</span>
                  </div>
                </div>

                <div id="dyh-monthly-chart" style="width: 200px;height: 140px;"></div>
              </div>
            </div>

            <div class="data-item">
              <div>
                <img :src="require('@/assets/leakage/terminals_count.png')" alt="" style="width: 56px;height: 56px;">
              </div>
              <div>
                <div style="font-size: 20px;padding: 5px;">挂表总数</div>
                <div class="value">
                  {{ dyhTerminalList ? dyhTerminalList.length : 0 }}
                  <span style="font-size: 16px;">个</span>
                </div>
                <!--              <div style="color: #0096ff;">-->
                <!--                {{ dyhTerminalList ? dyhTerminalList.length : 0 }}-->
                <!--              </div>-->
              </div>
            </div>
          </div>

          <el-tabs v-model="activeName" @tab-click="handleClick">
            <div class="option-tool">
              <div>
                <!--              当前区域：<span style="color: #1890ff;">{{ editingZone ? editingZone.areaName : '无' }}</span>-->
              </div>
              <div>
                <el-date-picker v-model="wsmQueryDate"
                                v-if="activeName==='1' || activeName==='2' || activeName==='4'"
                                size="mini"
                                type="daterange"
                                value-format="yyyy-MM-dd"
                                style="width: 210px;"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                @change="handleQueryDateChange">
                </el-date-picker>

                <el-date-picker v-model="wpsQueryDate"
                                v-if="activeName==='3'"
                                size="mini"
                                type="monthrange"
                                value-format="yyyy-MM"
                                style="width: 210px;"
                                range-separator="至"
                                start-placeholder="开始月份"
                                end-placeholder="结束月份"
                                @change="handleQueryDateChange">
                </el-date-picker>
              </div>
            </div>

            <el-tab-pane label="三日流量" name="1">
              <ThreeDaysFlow ref="refThreeDaysFlow"/>
            </el-tab-pane>

            <el-tab-pane label="最小流量" name="2" :lazy="true">
              <DyhMinNightFlow ref="refDyhMinNightFlow"/>
            </el-tab-pane>

            <el-tab-pane label="供水统计" name="3" :lazy="true">
              <WaterSupplyStatistics :addHeight="120" ref="refWaterSupplyStatistics"/>
            </el-tab-pane>

            <el-tab-pane label="报警信息" name="4" :lazy="true">
              <el-table v-loading="warnLoading" :data="dfqWarnDataList" border size="mini" :height="getWarnHeight"
                        style="margin-top: 10px;">
                <el-table-column type="index" width="35" align="center" label="#"/>
                <el-table-column label="报警时间" align="center" prop="startTime" width="180">
                  <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.StartTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <!--              <el-table-column label="名称" align="center" prop="targetName"/>-->
                <el-table-column label="报警状态" align="center" prop="warnStatus">
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.warn_status" :value="scope.row.warnStatus"/>
                  </template>
                </el-table-column>
                <el-table-column label="报警参数" align="center" prop="warnParamType">
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.warn_param_type" :value="scope.row.warnParamType"/>
                  </template>
                </el-table-column>
                <el-table-column label="报警类型" align="center" prop="warnType">
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.warn_type" :value="scope.row.warnType"/>
                  </template>
                </el-table-column>
                <el-table-column label="报警值" align="center" prop="warnValue"/>
                <el-table-column label="参考值" align="center" prop="referenceValue"/>
                <el-table-column label="差值" align="center" prop="value"/>
              </el-table>

              <pagination v-show="warnTotal>0"
                          :total="warnTotal"
                          :page.sync="warnQueryParams.pageNum"
                          :limit.sync="warnQueryParams.pageSize"
                          @pagination="getWarnDataList"
                          size="mini"
                          layout="total, sizes, prev, pager, next, jumper"
              />
            </el-tab-pane>

            <el-tab-pane label="基础信息" name="5" :lazy="true">
              <div style="width: 100%;margin-top: 10px;display: flex;justify-content: space-between;"
                   v-if="activeName==='5'">
                <div style="width: 58%;" :style="getMapHeight">
                  <L7Map @mapLoaded="handleMapLoaded"></L7Map>
                </div>

                <div style="width: calc(42% - 10px);">
                  <el-descriptions :column="1" border size="mini">
                    <el-descriptions-item label="大用户名称" :labelStyle="customLabelStyle">
                      {{ editingZone ? editingZone.name : '' }}
                    </el-descriptions-item>

                    <el-descriptions-item label="客户地址" :labelStyle="customLabelStyle">
                      {{ getBasicDyhValue('userAddress') }}
                    </el-descriptions-item>

                    <el-descriptions-item label="所属行业" :labelStyle="customLabelStyle">
                      {{ getBasicDyhValue('userTrade') }}
                    </el-descriptions-item>

                    <el-descriptions-item label="口径" :labelStyle="customLabelStyle">
                      {{ getBasicDyhValue('caliber') }}
                    </el-descriptions-item>

                    <el-descriptions-item label="负责人" :labelStyle="customLabelStyle">
                      {{ getBasicDyhValue('director') }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </ContentWrap>
  </div>
</template>

<script>
import moment from 'moment'
import RegionTree from "@/views/leakage/components/RegionTree.vue";
import L7Map from "@/components/L7Maps/map.vue";
import ThreeDaysFlow from '../components/ThreeDaysFlow.vue'
import DyhMinNightFlow from '../components/DyhMinNightFlow.vue'
import WaterSupplyStatistics from '../components/WaterSupplyStatistics.vue'
import {getDyhThreeDaysFlowData} from '@/api/leakage/terminalHistoryData'
import {listByQueryModel, getDyhOverviewData} from '@/api/leakage/freezeDyh'
import {getDyhSupplyAnalysisData} from "@/api/leakage/freezeDyh";
import {listWarnInfo} from '@/api/leakage/warnInfo'
import {getBasicDyhByAreaId} from '@/api/leakage/basicDyh'
import * as echarts from "echarts";
import {Marker, MarkerLayer, Popup} from "@antv/l7";
import {getZoneJoinTerminals} from "@/api/leakage/zoneJoin";

export default {
  name: 'dyh',
  dicts: ['warn_param_type', 'warn_status', 'warn_type'],
  components: {
    L7Map, RegionTree,
    ThreeDaysFlow, DyhMinNightFlow,
    WaterSupplyStatistics
  },
  data() {
    return {
      mapScene: undefined,
      terminalMarkerLayer: undefined,
      screenHeight: null,
      componentKey: 1,
      activeName: '1',
      editingZone: undefined,
      editingBasicDyh: undefined,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        frozenType: 'month'
      },
      wsmQueryDate: null,
      wpsQueryDate: null,
      // 遮罩层
      warnLoading: true,
      // 总条数
      warnTotal: 0,
      // 查询参数
      warnQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      dyhTerminalList: [],
      dyhDailyUsed: 0,
      dyhDailyOther: 0,
      dyhMonthlyUsed: 0,
      dyhMonthlyOther: 0,
      dfqWarnDataList: [],
      dyhDailyPipeChart: undefined,
      dyhMonthlyPipeChart: undefined,
      pieBaseOption: {
        color: ['#f8456b', '#0096ff',],
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: "vertical",
          left: 'left',
          top: 'middle',
          show: false
        },
        series: [
          {
            name: '大用户用水量占比',
            type: 'pie',
            radius: ['30%', '70%'],
            center: ['50%', '50%'],
            label: {
              show: false,
              position: 'center'
            },
            labelLine: {
              show: false
            },
            data: []
          }
        ]
      },
      customLabelStyle: {width: '17%', textAlign: 'right'},
    }
  },
  methods: {
    handleMapLoaded(scene) {
      this.mapScene = scene
      this.terminalMarkerLayer = new MarkerLayer();
    },
    initChart() {
      this.dyhDailyPipeChart = echarts.init(document.getElementById('dyh-daily-chart'), 'macarons')
      this.dyhMonthlyPipeChart = echarts.init(document.getElementById('dyh-monthly-chart'), 'macarons')
    },
    getBasicDyhValue(key) {
      return this.editingBasicDyh !== undefined ? this.editingBasicDyh[key] : ''
    },
    loadDyhOverviewData() {
      getDyhOverviewData({areaId: this.editingZone.areaId}).then(res => {
        const {dailyTotal, dailyUsed, monthlyTotal, monthlyUsed} = res.data
        this.dyhDailyUsed = dailyUsed
        this.dyhMonthlyUsed = monthlyUsed

        const dailyOther = dailyTotal - dailyUsed, monthlyOther = monthlyTotal - monthlyUsed
        this.dyhDailyOther = parseFloat(dailyOther.toFixed(2))
        this.dyhMonthlyOther = parseFloat(monthlyOther.toFixed(2))
        const dailyOption = JSON.parse(JSON.stringify(this.pieBaseOption))
        const monthlyOption = JSON.parse(JSON.stringify(this.pieBaseOption))

        dailyOption.series[0].data.push({name: '当前大用户日用水量', value: dailyUsed})
        dailyOption.series[0].data.push({name: '其他大用户日用水量', value: dailyOther})
        this.dyhDailyPipeChart.setOption(dailyOption)

        monthlyOption.series[0].data.push({name: '当前大用户月用水量', value: monthlyUsed})
        monthlyOption.series[0].data.push({name: '其他大用户月用水量', value: monthlyOther})
        this.dyhMonthlyPipeChart.setOption(monthlyOption)
      })
    },
    loadDyhTerminals(addMarker) {
      getZoneJoinTerminals({areaId: this.editingZone.areaId, terminalMark: 1}).then(res => {
        this.dyhTerminalList = res.rows
        if (addMarker) {
          this.addTerminalMarkerToMap()
        }
      })
    },
    addTerminalMarkerToMap() {
      let point
      if (this.terminalMarkerLayer) {
        this.terminalMarkerLayer.clear()
      }
      this.dyhTerminalList.forEach(t => {
        if (t.lng && t.lat) {
          point = [parseFloat(t.lng), parseFloat(t.lat)]

          const title = '大用户'
          const markerIcon = `/images/senior.png`
          const markerContent = `<div title="${title}"><img src="${markerIcon}" style="width: 40px;height: 40px;"></div>`
          let el = document.createElement('div')
          el.innerHTML = markerContent
          const marker = new Marker({element: el, draggable: false, offsets: [0, 0]}).setLnglat({
            lng: parseFloat(t.lng),
            lat: parseFloat(t.lat)
          })

          const data = t.realtimeGatherData
          const popup = new Popup({
            title: `${t.terminalName}`,
            lngLat: {
              lng: parseFloat(t.lng),
              lat: parseFloat(t.lat)
            },
            offsets: [0, 40],
            closeButton: false,
            html: `<div>
                  <div>瞬时流量：${data && data.instantNumber != null ? '<span style="color: limegreen;">' + data.instantNumber + '</span> m³/h' : '<span style="color: red;">-<span>'}</div>
                  <div>累计流量：${data && data.totalFlow != null ? '<span style="color: limegreen;">' + data.totalFlow + '</span> m³' : '<span style="color: red;">-<span>'}</div>
                  <div>压&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;力：${data && data.pressure != null ? '<span style="color: limegreen;">' + data.pressure + '</span> MPa' : '<span style="color: red;">-<span>'}</div>
                  <div>信号强度：${data && data.terminalCSQ != null ? '<span style="color: limegreen;">' + data.terminalCSQ + '</span>' : '<span style="color: red;">-<span>'}</div>
                  <div>更新时间：${data && data.ReadDate != null ? '<span style="color: limegreen;">' + data.ReadDate + '</span>' : '<span style="color: red;">-<span>'}</div>
                </div>`,
          });
          marker.setPopup(popup)

          marker.on('mouseover', (e) => {
            marker.openPopup()
          })

          marker.on('mouseout', (e) => {
            marker.closePopup()
          })

          this.terminalMarkerLayer.addMarker(marker);
        } else {
          this.$message.error(`【${t.areaName}】未在地图上定位`)
        }
      })
      this.mapScene.addMarkerLayer(this.terminalMarkerLayer);
      if (point) {
        this.mapScene.panTo(point)
      }
    },
    getWarnDataList() {
      this.warnLoading = true;
      this.warnQueryParams.targetID = this.editingZone.areaId
      this.warnQueryParams.targetType = 3
      if (this.wsmQueryDate) {
        this.warnQueryParams.queryStartDate = this.wsmQueryDate[0]
        this.warnQueryParams.queryEndDate = this.wsmQueryDate[1]
      }
      listWarnInfo(this.warnQueryParams).then(res => {
        this.warnTotal = res.total;
        this.dfqWarnDataList = res.rows;
        this.warnLoading = false;
      });
    },
    handleTreeLoaded() {
      this.loadDyhTerminals()
      this.loadDyhOverviewData()
    },
    handleNodeClick(node) {
      if (node.levelType !== '3') {
        this.editingZone = undefined
        this.$message.error('请选择大用户节点')
      } else {
        this.editingZone = node
        this.loadTabPaneData()
        this.loadDyhTerminals()
        this.loadDyhOverviewData()
      }
    },
    handleClick(tab, event) {
      this.loadTabPaneData()
    },
    resizeAllCharts() {
      this.$nextTick(() => {
        if (this.activeName === '1') {
          this.$refs.refThreeDaysFlow.resizeCharts(this.screenHeight)
        } else if (this.activeName === '2') {
          this.$refs.refDyhMinNightFlow.resizeCharts(this.screenHeight)
        } else if (this.activeName === '3') {
          this.$refs.refWaterSupplyStatistics.resizeCharts(this.screenHeight)
        }
      })
    },
    loadBasicDyh() {
      getBasicDyhByAreaId({areaId: this.editingZone.areaId}).then(res => {
        this.editingBasicDyh = res.data
      })
    },
    loadTabPaneData() {
      const query = {
        areaId: this.editingZone.areaId,
      }
      if (this.activeName === '1') {
        if (this.wsmQueryDate) {
          query.queryDates = this.wsmQueryDate.join(",")
        }
        getDyhThreeDaysFlowData(query).then(res => {
          this.$refs.refThreeDaysFlow.updateOption(res.data)
        })
      } else if (this.activeName === '2') {
        if (this.wsmQueryDate) {
          query.queryDates = this.wsmQueryDate.join(",")
          query.startDate = this.wsmQueryDate[0]
          query.endDate = this.wsmQueryDate[1]
        } else {
          const d1 = new moment().subtract(3, 'd').format('YYYY-MM-DD'),
            d2 = new moment().subtract(1, 'd').format('YYYY-MM-DD')
          query.queryDates = d1 + ',' + d2
          query.startDate = d1
          query.endDate = d2
        }
        query.frozenType = 'day'
        const p1 = getDyhThreeDaysFlowData(query)
        const p2 = listByQueryModel(query)
        Promise.all([p1, p2]).then((values) => {
          this.$refs.refDyhMinNightFlow.updateOption(values)
        })
      } else if (this.activeName === '3') {
        if (this.wpsQueryDate) {
          query.queryDates = this.wpsQueryDate.join(",")
        }
        getDyhSupplyAnalysisData(query).then(res => {
          this.$refs.refWaterSupplyStatistics.updateOption(res.data)
        })
      } else if (this.activeName === '4') {
        this.getWarnDataList()
      } else if (this.activeName === '5') {
        setTimeout(() => {
          this.loadDyhTerminals(true)
          this.loadBasicDyh()
        }, 500)
      }
    },
    handleQueryDateChange() {
      this.loadTabPaneData()
    }
  },
  created() {
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    getWarnHeight() {
      return this.screenHeight - 472
    },
    getMapHeight() {
      const h = this.screenHeight - 395
      return {height: h + 'px'}
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
    window.onresize = () => {
      this.screenHeight = document.body.clientHeight
      this.resizeAllCharts()
    }
  }
}

</script>

<style scoped lang="scss">
.option-tool {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.data-item {
  width: 180px;
  height: 180px;
  border: 1px solid #E3E3E3;
  line-height: 28px;
  padding-top: 18px;
  text-align: center;
  vertical-align: center;

  .value {
    background-color: #0096ff;
    color: #FFFFFF;
    font-size: 26px;
    font-weight: bold;
    padding: 13px 0;
  }
}

::v-deep .l7-popup .l7-popup-content {
  position: relative;
  padding: 16px;
  font-size: 14px;
  color: #FFFFFF;
  background: #5e72af;
  border-radius: 3px;
  -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

::v-deep .l7-popup-anchor-bottom .l7-popup-tip {
  -webkit-align-self: center;
  -ms-flex-item-align: center;
  align-self: center;
  border-top-color: #5e72af;
  border-bottom: none;
}
</style>
